### -*- coding: utf-8 -*- #############################################
# Разработано Паэглит Арвидом (http://arvid.dp.ua/)
# Все права защищены, 2007
#
# Developed by Paeglit Arvid (http://arvid.dp.ua/)
# All right reserved, 2007
#######################################################################
"""PrincipalSource installation methods

$Id: install.py 40 2007-12-11 17:09:25Z Arvi3D $

"""
__author__  = "Arvid"
__license__ = "GPL"
__version__ = "$Revision: 40 $"
__date__ = "$Date: 2007-12-11 17:09:25 +0000 (Tue, 11 Dec 2007) $"

from zope.app import zapi
from zope.app.sqlscript.sqlscript import SQLScript
from zope.interface import alsoProvides

from ks.sqltools.simplesqlui.mountpoint.mountpoint import MountPoint
from ks.sqltools.simplesqlui.factory.interfaces import ISqlFactory
from ks.sqltools.simplesqlui.factory.factory import Factory
from ks.script.sql.interfaces import ISQLScriptFactory
from ks.sqltools.simplesqlui.ds.interfaces import IDS
from ks.sqltools.simplesqlui.ds.ds import DS

from arvidcontent.principalsource.interfaces import IMountUser
from arvidcontent.principalsource.user.sql import all as user_all

def installPrincipalSource(context, name = u'mount_user', dsName = u'user',
                           factoryName = u'userFactory', scripts = user_all, **kw):
    sm = context.getSiteManager()

    sm[dsName] = DS()
    user = sm[dsName]
    sm.registerUtility(user, provided = IDS, name = dsName)

    for key, value in scripts.items():
        user[key] = zapi.getMultiAdapter((value, SQLScript), ISQLScriptFactory)()

    sm[factoryName] = Factory()
    userFactory = sm[factoryName]
    userFactory.ids = (u'auth_id', )
    userFactory.datasource = dsName
    userFactory.factory = u'User'
    sm.registerUtility(userFactory, provided = ISqlFactory, name = dsName)

    sm[name] = MountPoint(datasource = dsName, factory = dsName, isactivated = True)
    alsoProvides(sm[name], IMountUser)
    sm.registerUtility(sm[name], provided = IMountUser)

    return "OK"

def principalSourceReInstalled(context, **kw):
    del context.__parent__[context.__name__]
    return "OK"

def principalSourceInstalled(context, **kw):
    return "OK"

def deletePrincipalSource(context, name = u'mount_user', dsName = u'user',
                           factoryName = u'userFactory', **kw):
    sm = getSiteManager(context)
    try:
        sm.unregisterUtility(sm[name], provided = IMountUser)
        del sm[name]
    except (KeyError, TypeError):
        pass

    try:
        sm.unregisterUtility(sm[factoryName], provided=ISqlFactory)
        del sm[factoryName]
    except (KeyError, TypeError):
        pass

    try:
        sm.unregisterUtility(sm[dsName], provided=IDS)
        del sm[dsName]
    except (KeyError, TypeError):
        pass

    return 'OK'
